package cn.xyf.servicebase.handler;

import cn.xyf.commonutils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R error(Exception e){
        e.printStackTrace();
        return R.error().message("未知异常！原因是:"+e.getMessage());
    }

    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public R nullPointerError(NullPointerException e){
        e.printStackTrace();
        return R.error().message("空指针异常:"+e.getMessage());
    }

    @ExceptionHandler(MyException.class)
    @ResponseBody
    public R myError(MyException e){
        log.error(e.getMessage()); // 把日志信息写到文件中
        e.printStackTrace();
        return R.error().code(e.getCode()).message(e.getMsg());
    }
}
